#!/bin/bash

# Alias: Control permissions in addons with Multisite
# Menu: Web GUI
# Description:
#  Multisite can be used to manage the permissions of
#  the users in the addons e.g. if a user can edit NagVis
#  maps.

case "$1" in
   default)
       echo "on"
   ;;
   choices)
       echo "on: control user permissions"
       echo "off: disable permission control"
   ;;
   set)
       NAGVIS_CFG=${OMD_ROOT}/etc/nagvis/conf.d/authorisation.ini.php
       PNP_CFG=${OMD_ROOT}/etc/pnp4nagios/config.d/authorisation.php
       if [ "$2" == "on" ]; then
          cat > $NAGVIS_CFG <<EOF
; Created by OMD hook MULTISITE_AUTHORISATION
; Use the permissions files generated by multisite
[global]
authorisationmodule="CoreAuthorisationModMultisite"
authorisation_multisite_file="$OMD_ROOT/var/check_mk/wato/auth/auth.php"
EOF

          if [ ! -d $(dirname $PNP_CFG) ]; then
              mkdir $(dirname $PNP_CFG)
          fi
          cat > $PNP_CFG <<EOF
<?php
// Created by OMD hook MULTISITE_AUTHORISATION
// Use the permissions files generated by multisite
if(file_exists(OMD_SITE_ROOT.'/var/check_mk/wato/auth/auth.php')) {
    require_once(OMD_SITE_ROOT.'/var/check_mk/wato/auth/auth.php');

    // Before the first use of multisite the auth.php is empty and does not contain this
    // function. Do try to execute these functions in this case.
    if(function_exists('users_with_permission')) {
        \$conf['allowed_for_all_services'] = implode(',', users_with_permission('general.see_all'));
        \$conf['allowed_for_all_hosts'] = implode(',', users_with_permission('general.see_all'));
    }
}
?>
EOF
       else
          [ -f $NAGVIS_CFG ] && rm $NAGVIS_CFG
          [ -f $PNP_CFG ] && rm $PNP_CFG
       fi
       true
   ;;
esac
